#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
测试运行脚本
直接运行测试文件
"""

import os
import sys
import subprocess
import logging

# 设置日志级别
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
logger.info(f"添加到Python路径: {os.path.dirname(os.path.abspath(__file__))}")

def run_test_file(test_file):
    """运行单个测试文件"""
    try:
        logger.info(f"运行测试文件: {test_file}")
        # 使用二进制模式捕获输出，避免编码问题
        result = subprocess.run([sys.executable, test_file], 
                              check=False, 
                              capture_output=True)
        
        # 尝试解码输出，支持多种编码
        def decode_output(output):
            if not output:
                return ""
            
            encodings = ['utf-8', 'gbk', 'latin-1']
            for encoding in encodings:
                try:
                    return output.decode(encoding)
                except UnicodeDecodeError:
                    continue
            return "无法解码输出内容"
        
        # 打印输出
        stdout = decode_output(result.stdout)
        stderr = decode_output(result.stderr)
        
        if stdout:
            logger.info(f"\n{test_file} 标准输出:\n{stdout}")
        if stderr:
            logger.error(f"\n{test_file} 错误输出:\n{stderr}")
        
        return result.returncode == 0
        
    except Exception as e:
        logger.error(f"运行测试文件 {test_file} 时出错: {str(e)}")
        return False

if __name__ == "__main__":
    logger.info("开始运行测试...")
    
    # 测试文件列表
    test_files = [
        "tests/test_statistics_service.py",
        "tests/test_statistics_routes.py"
    ]
    
    all_success = True
    
    for test_file in test_files:
        success = run_test_file(test_file)
        if not success:
            all_success = False
    
    if all_success:
        logger.info("所有测试通过！")
        sys.exit(0)
    else:
        logger.error("测试失败！")
        sys.exit(1)